/*
  	Arkodroid - An Arduino Controller for Android
	Copyright (c) 2013 Miguel Monteiro, Eduardo Peixoto, Rui Pedro Carvalhal, André Braga.
	All rights reserved.
	http://code.google.com/p/arkodroid/
	
	Amarino API by Bonifaz Kaufmann - http://www.amarino-toolkit.net/
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package net.miguelmonteiro.android.arkodroid;

import net.miguelmonteiro.android.arkodroid.Checker.Resource;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import android.widget.ToggleButton;
import at.abraxas.amarino.Amarino;

public class Arkodroid extends Activity {
	// Variables
	public static int delay = 150;
	public static int threshold = 3;

	static boolean bdIsConnected = false;
	static int musicSelected;
	static long lastchanged;
	public static String[] values = { "0", "0" };
	public static String[] musics = new String[] {
        "Super Mario",
        "Star Wars",
        "Peer Gynt",
        "Smoke",
        "Natal"
    };
	
	public static final String TAG = "Arkodroid";
	
    /** Check if Bluetooth is ON **/
	@Override 
    protected void onResume() {
		super.onResume();
		
    	new Checker(this).pass(new Checker.Pass() {
    		@Override public void pass() {
    	    	// Nothing
    	 	}
    	}).check(Resource.BLUETOOTH);
    }

    /** Called when the activity is first created. **/
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        lastchanged = System.currentTimeMillis();
        
        SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        
        if (SP.getString("pref_control_mode_list", null).equals("1")) {
        	Log.d(TAG, "Accelerometer layout defined");
        	startActivity(new Intent(this, ArkodroidAccelerometer.class));
        	this.finish(); 
        }
        else if (SP.getString("pref_control_mode_list", null).equals("2")) {
        	Log.d(TAG, "Joysticks layout defined");
        	startActivity(new Intent(this, ArkodroidJoysticks.class));
        	this.finish(); 
        }
        else if (SP.getString("pref_control_mode_list", null).equals("3")) {
        	Log.d(TAG, "Buttons layout defined");
        	startActivity(new Intent(this, ArkodroidButtons.class));
        	this.finish(); 
        }
    }
	
	public static void doLightToggleClick(Activity activity, View view){
		if (bdIsConnected == true) {
            if (((ToggleButton) view).isChecked()) {
                Toast.makeText(activity, R.string.main_light_on, Toast.LENGTH_SHORT).show();
                Amarino.sendDataToArduino(activity, BluetoothConnect.DEVICE_ADDRESS, 'l', 1);
            } else {
                Toast.makeText(activity, R.string.main_light_auto, Toast.LENGTH_SHORT).show();
                Amarino.sendDataToArduino(activity, BluetoothConnect.DEVICE_ADDRESS, 'l', 0);            
            }
    	}
    	else {
    		((ToggleButton) view).setChecked(false);
    		Toast.makeText(activity, "Não conectado.", Toast.LENGTH_SHORT).show();
    	}
	}
	
	public static void sendValues(Activity activity){
		if (System.currentTimeMillis() - lastchanged > Arkodroid.delay){
			Amarino.sendDataToArduino(activity, BluetoothConnect.DEVICE_ADDRESS, 'A', Arkodroid.values.clone());
			lastchanged = System.currentTimeMillis();
		}
	}
	
	public static void sendStopValues(Activity activity){
		Amarino.sendDataToArduino(activity, BluetoothConnect.DEVICE_ADDRESS, 'A', Arkodroid.values.clone());
	}

	public static void selectMusic(final Activity activity){
        new AlertDialog.Builder(activity)
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setTitle(R.string.music_select)
	        .setSingleChoiceItems(musics, -1, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int item) {
	            	musicSelected = item;
	            }
	        })
	        .setPositiveButton(R.string.select, new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int item) {
	                //Toast.makeText(activity, Integer.toString(musicSelected), Toast.LENGTH_SHORT).show();
	    			Amarino.sendDataToArduino(activity, BluetoothConnect.DEVICE_ADDRESS, 'm', musicSelected);
	            }
	        })
	        .show();
	}
	
	public static void aboutDialog(final Activity activity){
		new AlertDialog.Builder(activity)
	        .setTitle(activity.getString(R.string.app_name) + " " + getVersion(activity))
	        .setView(View.inflate(activity, R.layout.about, null))
	        .setIcon(R.drawable.ic_launcher_small)
	        .setPositiveButton(R.string.about_email, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	        		Intent i = new Intent(Intent.ACTION_SEND);
	        		i.setType("message/rfc822");
	        		i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"mail@miguelmonteiro.net"});
	        		i.putExtra(Intent.EXTRA_SUBJECT, "Aplicação Arkodroid");
	        		i.putExtra(Intent.EXTRA_TEXT   , "");
	        		try {
	        			activity.startActivity(Intent.createChooser(i, "Enviar email..."));
	        		} catch (android.content.ActivityNotFoundException ex) {
	        		    Toast.makeText(activity, R.string.about_noemailinstalled, Toast.LENGTH_SHORT).show();
	        		}
	            }
	        }).setNeutralButton(R.string.about_website, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	            	Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/arkodroid/"));
	            	activity.startActivity(browserIntent);
	            }
	        }).setNegativeButton(R.string.back, null)
	        .show();
	}
	
	/** Hard "Back button" pressed **/
	@Override
    public void onBackPressed() {
		exit(this);
    }
	
	/** Exit App **/
	public static void exit(final Activity activity) {
		new AlertDialog.Builder(activity)
	    	.setTitle(R.string.exit)
	    	.setMessage(R.string.wantexit)
	    	.setIcon(android.R.drawable.ic_dialog_alert)
	    	.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int which) {
	    	    	Amarino.disconnect(activity, BluetoothConnect.DEVICE_ADDRESS);
	    			System.exit(0);
	    	    }
	    	})
	    	.setNegativeButton(R.string.no, null)
	    	.show();
	}
	
	/** Restart App **/
	public static void restart(Activity activity) {		
		Amarino.disconnect(activity, BluetoothConnect.DEVICE_ADDRESS);
		
		System.exit(2);
		
		Intent i = new Intent(activity, Arkodroid.class);
		activity.startActivity(i);
	}
    
	/** Menu creation **/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);        
        return true;
    }
    
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case R.id.connecttext:
            	startActivity(new Intent(this, BluetoothConnect.class));                
            	return true;
        	case R.id.musictext:
                Toast.makeText(this, R.id.musictext, Toast.LENGTH_SHORT).show();
        		return true;
            case R.id.settingstext:
            	finish();
            	startActivity(new Intent(this, net.miguelmonteiro.android.arkodroid.Settings.class));
                return true;
            case R.id.abouttext:
                Arkodroid.aboutDialog(this);
                return true;
        }
        return true;
    }
    
    /** Return the Version of the App **/
	private static String getVersion(Activity activity) {
		String version = "1.0";
		try {
			PackageInfo pi = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
            version = pi.versionName;
		} catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Package name not found", e);
        }
        return version;
    }
}
